﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using CoreEx.Common.Ioc;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
namespace CoreEx.Wcf.Common.Implementation
{
    /// <summary>
    /// Provides a default <see cref="WSHttpBinding"/> that is used only when 
    /// no other <see cref="Binding"/> service can be found.
    /// </summary>
    /// <remarks>
    /// If you want to use another type of <see cref="Binding"/>, implement the <see cref="IFactory{T}"/> interface 
    /// to create an appropriate <see cref="Binding"/> instance.
    /// </remarks>
    [PostProcessor]
    public class BindingPostProcessor : PostProcessorBase<Binding>
    {        
        public override void Process(IServiceRequestResult result)
        {
            if (result.OriginalResult == null)
            {

               
                
                
                //var binding = new WSHttpBinding();
                //binding.Security.Mode = SecurityMode.None;
                //binding.ReaderQuotas.MaxArrayLength = int.MaxValue;
                //binding.MaxReceivedMessageSize = int.MaxValue;
                //binding.MaxBufferPoolSize = int.MaxValue;
                //binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
                //binding.SendTimeout = new TimeSpan(0,10,0);
                //binding.ReceiveTimeout = new TimeSpan(0,10,0);
                //result.ActualResult = binding;

                var customBinding = new CustomBinding();

                var encodingBindingElement = new BinaryMessageEncodingBindingElement();
                encodingBindingElement.ReaderQuotas.MaxArrayLength = int.MaxValue;
                encodingBindingElement.ReaderQuotas.MaxDepth = int.MaxValue;
                encodingBindingElement.ReaderQuotas.MaxStringContentLength = int.MaxValue;                
                //var encodingBindingElement =
                //    result.Container.GetService<MessageEncodingBindingElement>("CustomMessageEncodingBindingElement",new TextMessageEncodingBindingElement());                
                var httpTransportBindingElement = new HttpTransportBindingElement();
                httpTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;                
                customBinding.Elements.Add(encodingBindingElement);
                customBinding.Elements.Add(httpTransportBindingElement);                               
                customBinding.SendTimeout = new TimeSpan(0,10,0);
                customBinding.ReceiveTimeout = new TimeSpan(0,10,0);                
                result.ActualResult = customBinding;
            }
        }
    }
}